package com.dc.project.basics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.annotation.DataScope;
import com.dc.common.constant.CustomSqlConstants;
import com.dc.common.exception.ServiceException;
import com.dc.common.utils.StringUtil;
import com.dc.common.vo.ResultVo;
import com.dc.project.basics.dao.BasCategoryDao;
import com.dc.project.basics.dto.BasCategoryDto;
import com.dc.project.basics.entity.BasCategory;
import com.dc.project.basics.service.BasCategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * 类别表(BasCategory)表服务实现类
 *
 * @author zhuangcy
 * @since 2021-06-11 14:39:55
 */
@Service("basCategoryService")
public class BasCategoryServiceImpl extends ServiceImpl<BasCategoryDao, BasCategory> implements BasCategoryService {

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return
     */
    @Override
    public ResultVo queryById(Serializable id) {
        return ResultVo.success().data(this.getById(id));
    }

    /**
     * 查询类别表列表
     *
     * @param dto
     * @return
     */
    @DataScope
    @Override
    public ResultVo queryByList(BasCategoryDto dto) {
        LambdaQueryWrapper<BasCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(null != dto.getCategoryId(), lambdaQueryWrapper -> lambdaQueryWrapper
                .ne(BasCategory::getCategoryId, dto.getCategoryId())
                .and(lambdaQuery -> lambdaQuery
                        .apply("!find_in_set({0},ancestors)", dto.getCategoryId())
                        .or()
                        .isNull(BasCategory::getAncestors)
                )
        ).and(StringUtils.isNotEmpty(dto.getCategoryCode()) || StringUtils.isNotEmpty(dto.getCategoryName()),
                lambdaQueryWrapper -> lambdaQueryWrapper
                        .like(StringUtils.isNotEmpty(dto.getCategoryCode()), BasCategory::getCategoryCode, dto.getCategoryCode())
                        .or()
                        .like(StringUtils.isNotEmpty(dto.getCategoryName()), BasCategory::getCategoryName, dto.getCategoryName())
        );
        List<BasCategory> list = this.list(queryWrapper);
        return ResultVo.success().data(list);
    }

    /**
     * 新增类别表
     *
     * @param basCategory
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo add(BasCategory basCategory) {
        LambdaQueryWrapper<BasCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BasCategory::getCategoryCode, basCategory.getCategoryCode())
                .last(CustomSqlConstants.LIMIT_1);
        BasCategory one = this.getOne(queryWrapper);
        if (null != one) {
            throw new ServiceException(StringUtil.format("{}该编码已存在", basCategory.getCategoryCode()));
        }
        changeAncestors(basCategory);
        return ResultVo.verify(this.save(basCategory));
    }

    private void changeAncestors(BasCategory basCategory) {
        if (null == basCategory.getParentId()) {
            basCategory.setAncestors("0");
            basCategory.setParentId(0);
        } else {
            BasCategory parent = this.getById(basCategory.getParentId());
            if (null == parent) {
                throw new ServiceException("未找到该父类别");
            }
            basCategory.setAncestors(parent.getAncestors() + "," + basCategory.getParentId());
        }
    }

    /**
     * 编辑类别表
     *
     * @param basCategory
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo edit(BasCategory basCategory) {
        LambdaQueryWrapper<BasCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BasCategory::getCategoryCode, basCategory.getCategoryCode())
                .last(CustomSqlConstants.LIMIT_1);
        BasCategory one = this.getOne(queryWrapper);
        if (null != one && !one.getCategoryId().equals(basCategory.getCategoryId())) {
            throw new ServiceException(StringUtil.format("{}该编码已存在", basCategory.getCategoryCode()));
        }
        changeAncestors(basCategory);
        return ResultVo.verify(this.updateById(basCategory));
    }

    /**
     * 根据主键删除类别表
     *
     * @param id 主键
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo delete(Serializable id) {
        return ResultVo.verify(this.removeById(id));
    }
}